local log     = require("modules.commhm.log")
local network = require("modules.commhm.network")
local utils   = require("modules.business_common.business_utils")

local ngx = ngx
local pairs = pairs
local table = table
local table_concat = table.concat

local request_log = function (...)
    return log.day_list('http_request', ...)
end

-- return : 'key1=value1&key2=value2&key3=value3...'
local make_param_string = function (params)
    local make_kv_str = function (key, value)
        return key .. '=' .. value
    end
    return table_concat(utils.table2list(params, make_kv_str), '&')
end

-- !@ http get request
local http_get_func = function( url, params, headers )
    headers = headers or {}
    headers["Connection"]     = "Keep-Alive"
    headers["User-Agent"]     = "mnw"

    local url_str = make_param_string(params)
    local uri = not url_str and url or url .. '?' .. url_str
    local code, body = network.getHttpPage( uri, headers )
    utils.hm.var_dump({ uri = uri, result = { code = code, body = body } })

    if code == 200 then
        return body or ''
    end

    request_log(utils.hm.to_str({ method = "GET", uri = uri, result = { code = code, body = body } }))
    return nil, code
end

-- !@ http post request
local http_post_func = function ( url, request, data, headers, timeout )
    timeout = timeout or 3000
    headers = headers or {}
    headers["Connection"]     = "Keep-Alive"
    headers["User-Agent"]     = "mnw"

    local url_str = make_param_string(request)
    local uri = not url_str and url or url .. '?' .. url_str
    local code, body = network.postHttpPage( uri, data, timeout, headers )
    utils.hm.var_dump({ uri = uri, body = data, result = { code = code, body = body } })

    if code == 200 then
        return (body or '')
    end

    request_log(utils.hm.to_str({ method = "POST", uri = uri, body = data, result = { code = code, body = body } }))
    return nil, code
end

-- !@ 导出模块
return {
    _VERSION = '0.0.1',
    Log      = request_log,
    Get      = http_get_func,
    Post     = http_post_func,
}